

package com.gc.server.service.impl;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.gc.server.dao.LinkHeadDao;
import com.gc.server.entity.LinkHeadEntity;
import com.gc.server.entity.RouteEntity;
import com.gc.server.vo.up.ShopUp;
import com.yf.response.RRException;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.excel.EasyExcel;
import com.gc.server.vo.down.ShopDown;

import java.io.InputStream;
import java.util.List;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;

import com.gc.server.dao.ShopDao;
import com.gc.server.entity.ShopEntity;
import com.gc.server.vo.ShopVo;
import com.gc.server.service.ShopService;
import com.yf.service.impl.BaseServiceImpl;

/**
 * 账户记录Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Fri Oct 16 18:10:43 CST 2020
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<ShopEntity> implements ShopService {

    private ShopDao dao;


    @Autowired
    public void setDao(ShopDao dao) {
        this.dao = dao;
        super.setBaseDao(dao);
    }


    @Override
    public List<ShopVo> findVo(ShopVo vo) {
        return dao.findVo(vo);
    }

    @Override
    public ShopVo getVo(Long id) {
        return dao.getVo(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveVo(ShopVo vo) {
        LinkHeadEntity headEntity = null;
        if(vo.getHead()!=null){
            headEntity = linkHeadDao.findByCode(vo.getHead().getCode());
        }
        if(headEntity!=null){
            vo.getEntity().setHead(headEntity.getId());
        }
        if(vo.getEntity().getCode()==null){
            dao.save(vo.getEntity());
            vo.getEntity().setCode("S" + vo.getEntity().getId());
        }else {
            vo.getEntity().setId(Long.valueOf(vo.getEntity().getCode().replace("S","")));
        }
        return dao.update(vo.getEntity());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateVo(ShopVo vo) {
        return dao.update(vo.getEntity());
    }


    @Override
    public void downLoad(HttpServletResponse response, List<ShopVo> list) {
        try {
            List<ShopDown> datas = list.stream().map(item -> new ShopDown(item)).collect(Collectors.toList());
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ShopDown.class).sheet("模板").doWrite(datas);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**内部方法**/


    /**
     * 外部方法实现
     **/

    @Override
    public List<ShopEntity> findByUserId(Long userId) {
        return dao.findByUserId(userId);
    }

    @Override
    public List<ShopEntity> findByRouteId(Long routeId) {
        return dao.findByRouteId(routeId);
    }

    @Override
    public void upload(InputStream file) {
        EasyExcel.read(file, ShopUp.class, new UploadDataListener()).sheet().doRead();
    }

    class UploadDataListener extends AnalysisEventListener<ShopUp> {


        @Override
        @Transactional(rollbackFor = Exception.class)
        public void invoke(ShopUp upVo, AnalysisContext analysisContext) {
            saveVo(upVo.toVo());
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        }

    }

    @Autowired
    private LinkHeadDao linkHeadDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Long userId, ShopEntity shopEntity) {
        if (shopEntity.getShopName() == null || shopEntity.getShopName().equals("")) {
            throw new RRException("请填写名字");
        }
        //新增
        if (shopEntity.getId() == null) {
            dao.save(shopEntity);
        } else { //修改
            dao.update(shopEntity);
            //先删除所有的
            dao.rmUser(userId, shopEntity.getId());
        }
        //添加药店
        if (shopEntity.getUserIds() != null) {
            List<Long> userIds = shopEntity.getUserIds().stream().filter(s -> s != null).distinct().collect(Collectors.toList());
            if (userIds.size() > 0) {
                dao.addUser(shopEntity.getId(), userIds);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Long userId, List<Long> shopIds) {
        //先删除所有跟当前用户有关的
        dao.rmUserByUserId(userId);
        //去重
        shopIds = shopIds.stream().filter(shopId->shopId!=null).distinct().collect(Collectors.toList());
        if(shopIds.size()>0){
            dao.addShop(shopIds,userId);
        }
    }
}
